package com.culture.bootdemo.utils.fileutils;

import com.culture.bootdemo.model.enums.FileSuffixNameEnum;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Author: wenjl
 * @Date: 2021/3/15 16:29
 * @Description: hutool工具  csv文件生成和读取
 */
@Slf4j
public class TxtUtils {

    private final static String path = "E:\\csvfile\\20200427";


    /**
     * @param list     数据集合
     * @param path     路径
     * @param fileName 文件名，需要加扩展名(.txt)
     *                 换行符：
     *                 \r Mac
     *                 \n Unix/Linux
     *                 \r\n Windows
     *                 可用代码：System.lineSeparator() 替换
     */
    public static void writeToTxt(List<String> list, String path, String fileName) {
        if (StringUtils.isBlank(path) || StringUtils.isBlank(fileName)) {
            return;
        }
        if (fileName.contains(FileSuffixNameEnum.xlsx.getName()) || fileName.contains(FileSuffixNameEnum.xls.getName())) {
            return;
        }
        File parent = new File(path);
        if (!parent.exists()) {
            if (!parent.mkdirs()) {
                log.error("writeToTxt 创建目录失败");
            }
        }
        FileOutputStream outSTr = null;
        BufferedOutputStream buff = null;

//        String enter = "\r\n";
        String enter = System.lineSeparator();
        StringBuffer write;
        path = path.concat(File.separator).concat(fileName);
        try {
            outSTr = new FileOutputStream(path);
            buff = new BufferedOutputStream(outSTr);
            for (String o : list) {
                write = new StringBuffer();
                write.append(o);
                write.append(enter);
                buff.write(write.toString().getBytes(StandardCharsets.UTF_8));
            }
            buff.flush();
        } catch (Exception e) {
            log.error("TxtUtils 写txt文件报错：", e);
        } finally {
            try {
                if (null != buff) {
                    buff.close();
                }
                if (null != outSTr) {
                    outSTr.close();
                }
            } catch (Exception e) {
                log.error("TxtUtils 写txt文件关闭流报错：", e);
            }
        }
    }


    /**
     * 读取文件 按行读取
     *
     * @param fileName 全路径文件名
     * @return
     */
    public static List<String> readFileTxt(String fileName) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(fileName)) {
            return result;
        }
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                if (StringUtils.isNotBlank(tempStr)) {
                    result.add(tempStr);
                }
            }
            reader.close();
            return result;
        } catch (IOException e) {
            log.error("TxtUtils 读txt文件报错：", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    log.error("TxtUtils 读txt文件关闭流报错：", e1);
                }
            }
        }
        return result;
    }

    /**
     * 读取文件 按字节读取
     *
     * @param fileName 全路径文件名
     * @param split    分隔符
     * @return
     */
    public static List<String> readFileByteTxt(String fileName, String split) {
        List<String> result = Lists.newArrayList();
        if (StringUtils.isBlank(fileName) || StringUtils.isBlank(split)) {
            return result;
        }
        File file = new File(fileName);
        InputStream in = null;
        byte[] tempByte = new byte[1024];
        String str;
        try {
            in = new FileInputStream(file);
            while (in.read(tempByte) != -1) {
                str = new String(tempByte);
                //分隔符
                String[] array = str.split(split);
                result.addAll(Arrays.asList(array));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 读取文件
     *
     * @param fileName url路径  例如：http://10.4.14.57:8880/smart/static/4471d70cf3c8b39f2fe67f9d9bd8dfa9.txt
     * @return
     */
    public static String readUrl(String fileName) {
        String read;
        List<String> list = Lists.newArrayList();
        try {
            URL url = new URL(fileName);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setConnectTimeout(50000);
            urlCon.setReadTimeout(50000);
            BufferedReader br = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            while ((read = br.readLine()) != null) {
                list.add(read);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return String.valueOf(list.size());
    }


    /**
     * 读取文件并输出流
     *
     * @param response
     * @param path
     */
    public static void readAndOut(HttpServletResponse response, String path) {
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(path);
            //设置文件ContentType类型
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("readAndOut 读取服务器文件失败1:", e);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (Exception e) {
                log.error("readAndOut 读取服务器文件失败2:", e);
            }
        }

    }

    public static void main(String[] args) {
        List<String> list = readFileByteTxt("E:\\项目架构\\2.txt", "#");
        System.out.println(list);
    }


}
